<template>
  <div>
    <el-table :data="media.inputChannel.channels"  @row-click='handleCurrentChanges' style="width: 100%"  highlight-current-row>
      <el-table-column
        :label="$t('message.medias.streamCnt')"
        prop="streamCnt">
      </el-table-column>
      <el-table-column  :label="$t('message.medias.dev')" >
        <template  slot-scope="scope">   
          <span>{{scope.row.devs }}</span>
        </template> 
      </el-table-column>
    </el-table>
    <setForm id="1" v-show="show">       
       <template slot="boxTop">{{$t('message.medias.channelSetting')}}</template>
          <template slot="boxMain">                
            <el-row>
            <el-col :span="4" class="col4">    
              <div class="span3">                   
                <label>{{$t('message.medias.dev')}}</label>  
              </div>
            </el-col>
             <el-col :span="20" class="span17">        
              <el-checkbox-group v-model="currentRow.devs" style="margin-top:10px;" :disabled="isHideAll">
                <el-checkbox v-for="(option, index) in devsToSelect" :disabled="index > 1" :label="option.value" :key="option.value" @change="onSelectDevChange($event, option.value)" >{{option.text}}</el-checkbox>
              </el-checkbox-group>
            </el-col>
          </el-row>
          <el-button  class="btnsave" @click="onSaveChannel"  :disabled="isHideAll">{{$t('message.save')}}</el-button>
          </template>
    </setForm>
    <!-- 媒体流 -->
    <setForm id="2" v-show="show">       
       <template slot="boxTop">{{$t('message.medias.streamSetting')}}</template>
          <template slot="boxMain">  
            <el-table :data="streamData" min-height="320"  style="width: 100%" @expand-change="onClickExpand">
                <el-table-column
                  :label="$t('message.name')"
                  prop="name">
                </el-table-column>
                <el-table-column
                  :label="$t('message.medias.hasAudio')">
                  <template  slot-scope="scope">   
                    <span>{{ scope.row.hasAudio?$t('message.yes'):$t('message.no') }}</span>
                  </template> 
                </el-table-column>
                <el-table-column
                  :label="$t('message.medias.aProto')">
                  <template  slot-scope="scope">   
                    <span>{{ scope.row.hasAudio ? scope.row.audio.protocol : '' }}</span>
                  </template> 
                </el-table-column>
                <!-- <el-table-column 
                  :label="$t('message.medias.aProto')"
                  prop="audio.protocol">
                </el-table-column> -->
                <el-table-column
                  :label="$t('message.medias.hasVedio')">
                  <template  slot-scope="scope">   
                    <span>{{ scope.row.hasVideo?$t('message.yes'):$t('message.no') }}</span>
                  </template> 
                </el-table-column>
                <el-table-column
                  :label="$t('message.medias.vProto')"
                  prop="video.protocol">
                </el-table-column>
                <el-table-column
                  :label="$t('message.medias.rtspUrl')"
                  prop="rtspUrl">
                </el-table-column>
                <el-table-column :label="$t('message.medias.operation')" min-width="140px;">
                  <template slot-scope="scope">
                    <el-button v-show="scope.row.hasAudio"
                      size="mini"
                      @click="editStreamAudio(scope.$index, scope.row)">{{$t('message.medias.audioSetting')}}</el-button>  
                    <el-button v-show="scope.row.hasVideo"
                      size="mini"
                      @click="editStreamVideo(scope.$index, scope.row)">{{$t('message.medias.videoSetting')}}</el-button>  
                  </template>
                </el-table-column>
                <el-table-column type="expand" :label="$t('message.medias.expand')" width="60px;">
                  <template slot-scope="props">
                    <el-form label-position="left" inline class="demo-table-expand" >                      
                      <el-form-item :label="$t('message.audio')+$t('message.medias.'+label)+':'" v-for="label in aExpands" :key="label">
                        <span>{{props.row.report.audio[label]}}</span>
                      </el-form-item>  <br>                   
                      <el-form-item v-show="props.row.hasVideo" :label="$t('message.video')+$t('message.medias.'+label)+':'" v-for="label in vExpands" :key="label">
                        <span>{{props.row.report.video[label]}}</span>
                      </el-form-item>                     
                    </el-form>
                  </template>
                </el-table-column>
              </el-table>  
          </template>
    </setForm>
    <!-- 字幕 -->
    <setForm id="3" v-show="showSubtitle">       
       <template slot="boxTop"> {{$t('message.medias.subtitle')}}</template>
          <template slot="boxMain">  
            <div>          
              <el-table :data="subtitleData"  style="width: 100%">
                <el-table-column
                  :label="$t('message.medias.enable')">
                  <template slot-scope="scope">
                    <span>{{scope.row.enable? $t('message.systems.enable'): $t('message.systems.disable')}}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  :label="$t('message.medias.fontsize')"
                  prop="fontSize">
                </el-table-column>
                <el-table-column :label="$t('message.medias.foregrounnd')">
                  <template slot-scope="scope">
                    <div :style="'width:60px;height:24px;border-style: solid;border-width:1px;border-color:#606266;background-color:' + scope.row.foreColor"></div>
                  </template>
                </el-table-column>
                <el-table-column
                  :label="$t('message.medias.type')"
                  prop="type">
                </el-table-column>
                <el-table-column :label="$t('message.medias.content')">
                  <template slot-scope="scope">{{showContent(scope.row)}}</template>
                </el-table-column>
                <el-table-column :label="$t('message.medias.operation')">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      @click="editSubtitle(scope.$index, scope.row)">{{$t('message.medias.edit')}}</el-button>             
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
    </setForm>
    <!-- 背景图 -->
     <setForm id="4" v-show="showBackGround">       
       <template slot="boxTop">{{$t('message.medias.backgroundImg')}}</template>
          <template slot="boxMain">  
           <el-row>
            <el-col :span="12" class="col4">                            
                <img :src="imgFile" id="img" style="width:400px;height:auto;" >               
            </el-col>
            <el-col :span="12" class="col20">
              <el-checkbox v-model="bgEnable" @change="onBgEnableChanged">{{$t('message.medias.enable')}}</el-checkbox>  
              <el-upload
                ref="upload"
                id="imgUploadFile"
                :limit="1"
                :multiple="false"
                action=""
                :before-upload="onFileChange"                
                :on-preview="handlePictureCardPreview"
                :on-exceed="onFilesOutOfMax"
                accept=".jpg"
                list-type="picture-card">
                <i class="el-icon-plus"></i>
              </el-upload> 
               <el-button  @click="uploadBgImg" style="margin-top:40px;">{{$t('message.save')}}</el-button>             
              </el-col>
          </el-row>
          </template>
    </setForm>
    <!-- 字幕弹窗 -->
   <el-dialog :title="$t('message.medias.subtitle')" :visible.sync="subtitleVisible"  width="660px" @open="onSubDialogOpen" id="subDialog">
    <canvas id="myCanvas" width="576;" height="324"></canvas>      
    <el-form label-position="right" label-width="80px" :model="subtitle" size="mini">
      <el-form-item :label="$t('message.medias.enable')">
        <el-checkbox v-model="subtitle.enable" >{{$t('message.medias.enable')}}</el-checkbox>
      </el-form-item>
      <el-form-item :label="$t('message.medias.type')">
        <el-select  v-model="subtitle.type" @change="onSubTypeChange">
          <el-option v-for="option in subtitleTyps" :key="option" :value="option">{{option}}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('message.medias.fontsize')" >
        <el-input v-model="subtitle.fontSize" placeholder="" type="number"></el-input> 
      </el-form-item>
      <el-form-item :label="$t('message.medias.foregrounnd')"> 
        <el-select  v-model="subtitle.foreColor">
          <el-option v-for="option in colorOptions" :key="option.value" :value="option.value" :label="option.text"></el-option>
        </el-select>   
      </el-form-item>         
      <el-form-item :label="$t('message.medias.horizontal')">
        <el-slider v-model="subtitle.pos.x" ></el-slider>
      </el-form-item>         
      <el-form-item :label="$t('message.medias.vertical')">
        <el-slider v-model="subtitle.pos.y" ></el-slider>
      </el-form-item>         
      <el-form-item :label="$t('message.medias.content')" v-show="showSubContent">
        <el-input v-model="subtitle.content" placeholder="" ></el-input>
      </el-form-item>  
      <el-form-item>
      <el-button @click="subtitleVisible = false">{{$t('message.cancel')}}</el-button>
      <el-button  @click="onSaveSutitle">{{$t('message.ok')}}</el-button>
      </el-form-item>  
    </el-form>
  </el-dialog>     
    <!-- 视频弹窗 -->
   <el-dialog :title="$t('message.medias.videoSetting')" :visible.sync="streamVisible" width="660px">
    <el-form  label-width="120px" ref="video" :model="video" :rules="streamRules" size="mini">  
      <el-form-item :label="$t('message.medias.protocol')">  
        <select v-model="video.protocol">
          <!-- <option v-for="option in topics" :key="option">{{option}}</option> -->
          <option v-for="option in vprotos" :key="option">{{option}}</option>
        </select>
      </el-form-item>       
      <el-form-item :label="$t('message.medias.fmtType')" prop="resolution"> 
        <select v-model="video.resolution">
          <option v-for="option in resolutions" :key="option">{{option}}</option>
        </select>
      </el-form-item>     
      <el-form-item :label="$t('message.medias.frameRate')"  prop="framerate">     
        <el-input v-model="video.framerate"  type="number" class="layui-input" :name="$t('message.medias.frameRate')" ></el-input>   
      </el-form-item>    
      <el-form-item :label="$t('message.medias.bitRate')"  prop="bitRate">    
        <select v-model="video.bitRate">
          <option v-for="option in bitRates" :key="option.value" :value="option.value">{{option.name}}</option>
        </select> 
      </el-form-item>        
      <el-form-item :label="$t('message.medias.rateControl')"  >
        <select v-model="video.rateControl">
          <option v-for="option in rateControls" :key="option">{{option}}</option>
        </select>
      </el-form-item>      
      <el-form-item :label="$t('message.medias.gops')"  prop="gops">         
        <el-input v-model="video.gops"  type="number" class="layui-input" :name="$t('message.medias.gops')" ></el-input>
      </el-form-item>    
      <el-form-item :label="$t('message.medias.qmin')" prop="qpmin">  
        <el-input v-model="video.qpmin" type="number" class="layui-input" :name="$t('message.medias.qmin')" ></el-input>
      </el-form-item>      
      <el-form-item :label="$t('message.medias.qmax')"  prop="qpmax">   
        <el-input v-model="video.qpmax" type="number" class="layui-input" :name="$t('message.medias.qmax')" ></el-input>
      </el-form-item>      
      <el-form-item :label="$t('message.medias.scaleMode')" prop="scaleMode">
        <select v-model="video.scaleMode">
          <option v-for="option in scaleModes" :key="option.value" :value="option.value">{{option.name}}</option>
        </select> 
      </el-form-item>     
      <el-form-item >
        <el-button  @click="onSaveStreamVideo">{{$t('message.ok')}}</el-button>
        <el-button @click="streamVisible = false">{{$t('message.cancel')}}</el-button>
      </el-form-item>    
    </el-form>    
  </el-dialog>  
    <!-- 音频流弹窗 -->
   <el-dialog :title="$t('message.medias.audioSetting')" :visible.sync="audioVisible" width="660px">
    <el-form  label-width="120px" ref="audio" :model="audio" size="mini">     
      <el-form-item :label="$t('message.medias.protocol')">        
        <select v-model="audio.protocol">
          <option v-for="option in aprotos" :key="option">{{option}}</option>
        </select>
      </el-form-item>    
      <el-form-item >
        <el-button  @click="onSaveStreamAudio">{{$t('message.ok')}}</el-button>
        <el-button @click="audioVisible = false">{{$t('message.cancel')}}</el-button>
      </el-form-item>    
    </el-form>    
  </el-dialog>      
    <!-- 图片预览弹窗 -->
    <el-dialog :visible.sync="dialogVisible" size="tiny">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { api, getHostName } from "../../../../libs/api";
import setForm from "@/components/setForm";
import mylist from "@/components/MyList";
import { mapState } from "vuex";
import topTable from "../../../../components/topTable";
import topTable1 from "../../../../components/topTable1";
import ebus from "@/libs/ebus";
import debugCfg from "../../../../libs/debugCfg";
import { getMyCanvas } from "../../../../libs/canvas"
import { getInputChStreamReport } from "@/store/actions/media"
import axios from 'axios'
export default {
  created() {
    this.loadData();
    this.intervalGetInputChnnlInfo();    
  },
  beforeDestroy() {
    this.onClearInterval();
  },
  watch:{
    subtitle: {
      handler: function(val, oldVal) {
        this.drawLayout();
      },
      deep: true
    }
  },
  computed: {
    ...mapState(["media"]),
    ...mapState(["system"]),
    tableData() {
      var items = [];
      if (this.media.inputChannel.channels) {
        items = this.media.inputChannel.channels;
      }
      return items;
    },
    streamData() {
      var items = [];
      if (
        this.media.inputChannel &&
        this.media.inputChannel.channels &&
        this.media.inputChannel.channels[this.index].stream
      ) {
        items = this.media.inputChannel.channels[this.index].stream;
      }
      return items;
    },
    devsToSelect() {
      var items = [];
      var devs = this.media.inputDev.devs;
      if (devs) {
        for (var i = 0; i < devs.length; i++) {
          items.push({
            text: devs[i].name,
            value: i
          });
        }
      }
      return items;
    },
    devsToSelectDisabled() {
      return this.index == 2;
    },
    imgFile1(){
      var cur = this.media.inputChannel.channels[this.index]
      var indexOfDefault = cur.imgFile.indexOf("default");
      return `http://${getHostName()}:8080/_${cur.imgFile.substr(indexOfDefault, cur.imgFile.length - indexOfDefault)}`;
    },
    topics() {
      var topics = this.system.topics      
      topics = _.filter(topics, item => {
        return item.topicId.includes('vcodec')
      })      
      return topics
    },
    maxSelectCnt(){
      var count = 2;
      if(this.media.inputDev.cnt == 5){
        count = 4
      }
      return count
    }
  },
  data() {
    var framRateRule = (rule, value, callback) => {
      this.checkNumVal(value, 1, 60, callback);
    };
    var bitRateRule = (rule, value, callback) => {
      this.checkNumVal(value, 128000, 40000000, callback);
    };
    var gopsRule = (rule, value, callback) => {
      this.checkNumVal(value, 1, 5, callback);
    };
    var qpminRule = (rule, value, callback) => {
      this.checkNumVal(value, 1, 100, callback);
    };
    var qpmaxRule = (rule, value, callback) => {
      this.checkNumVal(value, 1, 100, callback);
    };

    return {   
      fileList: [],   
      defaultUrl: '',
      timer: [null, null, null],
      subTimer: null,
      previewTimer: null,
      dialogImageUrl: '',
      reportInterval: null,
      expanded: false,
      dialogVisible: false,
      file: null,
      showSubContent: false,
      interval: null,
      showSubtitle: false,
      audio: {},
      video: {},
      audioVisible: false,
      showBackGround: false,
      bgEnable: false,
      isHideAll: false,
      imgFile:
        "http://" + getHostName() + ":8080/_resources/custom/background.jpg",
      formLabelWidth: 40,
      subtitleData: [
        {
          index: 0,
          content: ""
        }
      ],
      streamData1: [
        {
          name: "",
          rtspUrl: ""
        }
      ],
      subtitleVisible: false,
      streamVisible: false,
      currentSubtitle: {},
      currentRow: {},
      show: false,
      aproto: "AAC",
      aprotos: ["AAC", "G711A", "G711U", "G722"],
      vproto: "H264",
      vprotos: ["H264"],
      aExpands: ["protocol", "bitrate", "channels"],
      vExpands: ["protocol", "bitrate", "framerate", "resolution"],
      subtitleIndex: 0,
      subtitle: {
        base:{
          h: 0,
          v: 0
        },
        pos:{
          x: 0,
          y: 0
        },
        fontSize: 20,
        foreColor: '#ffffff',
        enable: false,
        index: -1,
        content: '',
        type: ''
      },
      streamIndex: 0,
      rateControl: "vbr",
      scaleMode: "fullScreen",
      stream: {},
      index: 0,
      channel: 1,
      devCnt: 2,
      capPerDec: 2,
      devs: [1, 2, 3],
      resolutions: ["CIF", "720P", "1080P", "4K"],
      rateControls: ["vbr", "cbr"],
      bitRates: [
        {
          name: "128",
          value: 128 * 1000
        },
        {
          name: "384",
          value: 384 * 1000
        },
        {
          name: "500",
          value: 500 * 1000
        },
        {
          name: "1000",
          value: 1000 * 1000
        },
        {
          name: "1500",
          value: 1500 * 1000
        },
        {
          name: "2000",
          value: 2000 * 1000
        },
        {
          name: "2500",
          value: 2500 * 1000
        },
        {
          name: "3000",
          value: 3000 * 1000
        },
        {
          name: "4000",
          value: 4000 * 1000
        },
        {
          name: "5000",
          value: 5000 * 1000
        },
        {
          name: "6000",
          value: 6000 * 1000
        },
        {
          name: "8000",
          value: 8000 * 1000
        },
        {
          name: "10000",
          value: 10000 * 1000
        },
        {
          name: "20000",
          value: 20000 * 1000
        },
        {
          name: "40000",
          value: 40000 * 1000
        }
      ],
      scaleModes: [
        {
          name: this.$t("message.medias.fullscreen"),
          value: "fullscreen"
        },
        {
          name: this.$t("message.medias.uniform"),
          value: "uniform"
        },
        {
          name: this.$t("message.medias.middle"),
          value: "middle"
        }
      ],
      dev: "",
      enable: true,
      subtitletype: "",
      fontsize: 12,
      content: "example",
      foregrounnd: "#409EFF",
      background: "#409EFF",
      subtitleTyps: [
        "text",
        "ipaddr",
        "devName",
        "normaltime",
        "timewithweekday"
      ],
      subColumns: [
        {
          label: "content",
          prop: "content"
        },
        {
          label: "index",
          prop: "index"
        }
      ],
      columns: [
        {
          label: this.$t("message.medias.streamCnt"),
          prop: "streamCnt"
        },
        {
          label: this.$t("message.medias.dev"),
          prop: "devs"
        }
      ],
      subtitlecolumns: [
        {
          label: "type",
          prop: "type"
        }
      ],
      colorOptions: [
        {
          value: "#000000",
          text: "black"
        },
        {
          value: "#ffffff",
          text: "white"
        },
        {
          value: "#0000ff",
          text: "blue"
        },
        {
          value: "#a52a2a",
          text: "brown"
        },
        {
          value: "#808080",
          text: "gray"
        },
        {
          value: "#008000",
          text: "green"
        },
        {
          value: "#ff0000",
          text: "red"
        },
        {
          value: "#ffff00",
          text: "yellow"
        },
        {
          value: "#1abc9c",
          text: "turquoise"
        },
        {
          value: "#2ecc71",
          text: "emerald"
        },
        {
          value: "#3498db",
          text: "peter river"
        },
        {
          value: "#9b59b6",
          text: "amethyst"
        },
        {
          value: "#34495e",
          text: "wet asphalt"
        },
        {
          value: "#16a085",
          text: "green sea"
        },
        {
          value: "#27ae60",
          text: "nephritis"
        },
        {
          value: "#2980b9",
          text: "belize hole"
        },
        {
          value: "#8e44ad",
          text: "wisteria"
        },
        {
          value: "#2c3e50",
          text: "midnight blue"
        },
        {
          value: "#f1c40f",
          text: "sun flower"
        },
        {
          value: "#e67e22",
          text: "carrot"
        },
        {
          value: "#e74c3c",
          text: "alizarin"
        },
        {
          value: "#ecf0f1",
          text: "clouds"
        },
        {
          value: "#95a5a6",
          text: "concrete"
        },
        {
          value: "#f39c12",
          text: "orange"
        },
        {
          value: "#d35400",
          text: "pumpkin"
        },
        {
          value: "#c0392b",
          text: "pomegranate"
        },
        {
          value: "#bdc3c7",
          text: "silver"
        },
        {
          value: "#7f8c8d",
          text: "asbestos"
        }
      ],
      streamRules: {
        framerate: [
          { required: true, message: this.$t("message.medias.required") },
          { validator: framRateRule }
        ],
        gops: [
          { required: true, message: this.$t("message.medias.required") },
          { validator: gopsRule }
        ],
        qpmin: [
          { required: true, message: this.$t("message.medias.required") },
          { validator: qpminRule }
        ],
        qpmax: [
          { required: true, message: this.$t("message.medias.required") },
          { validator: qpmaxRule }
        ]
      }
    };
  },
  components: {
    setForm,
    mylist,
    topTable,
    topTable1
  },
  methods: {
    loadData(){
      ebus.emit("getInputChannelInfo", this);
    },
    onSaveStreamVideo() {
      if (
        !this.video.framerate ||
        this.video.framerate < 1 ||
        this.video.framerate > 60 ||
        !this.video.bitRate ||
        this.video.bitRate < 128000 ||
        this.video.bitRate > 40000000 ||
        !this.video.gops ||
        this.video.gops < 1 ||
        this.video.gops > 5 ||
        !this.video.qpmin ||
        this.video.qpmin < 1 ||
        this.video.qpmin > 100 ||
        !this.video.qpmax ||
        this.video.qpmax < 1 ||
        this.video.qpmax > 100
      ) {
        return;
      }
      var option = {
        protocol: this.video.protocol,
        resolution: this.video.resolution,
        framerate: parseInt(this.video.framerate),
        rateControl: this.video.rateControl,
        bitRate: parseInt(this.video.bitRate),
        gops: parseInt(this.video.gops),
        qpmin: parseInt(this.video.qpmin),
        qpmax: parseInt(this.video.qpmax),
        scaleMode: this.video.scaleMode
      };

      api.onRequest(
        "$method.$set.media.mi.ch" +
          this.currentRow.index +
          ".stream" +
          this.video.index +
          ".vcodec",
        JSON.stringify(option),
        null,
        null,
        function(msg, reqReply) {
          var res = JSON.parse(msg);
          if (res.code == 0) {
            this.streamVisible = false;
            this.notification("Success", "");
          } else {
            this.showCodeMsg(res.code, this, res.msg);
          }
          ebus.emit("getInputChannelInfo", this);
        }.bind(this)
      );
    },
    onSaveStreamAudio() {
      var option = {
        protocol: this.audio.protocol
      };
      api.onRequest(
        "$method.$set.media.mi.ch" +
          this.currentRow.index +
          ".stream" +
          this.audio.index +
          ".acodec",
        JSON.stringify(option),
        null,
        null,
        function(msg, reqReply) {
          var res = JSON.parse(msg);
          if (res.code == 0) {
            this.audioVisible = false;
            this.notification("Success", "");
          } else {
            this.showCodeMsg(res.code, this, res.msg);
          }
          ebus.emit("getInputChannelInfo", this);
        }.bind(this)
      );
    },
    handleCurrentChanges(val) {    
      var channelCnt = this.media.inputChannel.cnt - 1;
      this.defaultUrl = val.imgFile;
      if(val.imgFile && val.imgFile.includes('/default')) {
        this.imgFile = 'http://' + getHostName() + ":8080/_" + val.imgFile.substr(val.imgFile.indexOf('default'), val.imgFile.length -val.imgFile.indexOf('default'))
      } else if(val.imgFile && val.imgFile.includes('/resources')) {
        this.imgFile = 'http://' + getHostName() + ":8080/_" + val.imgFile.substr(val.imgFile.indexOf('resources'), val.imgFile.length -val.imgFile.indexOf('resources'))
      } else{
        this.imgFile = '';
      }   
      this.subtitleData = []; 
      this.subtitleData = val.subtitle;
      this.currentRow = val;
      this.index = val.index;
      this.show = true;
      this.bgEnable = val.enable;
      this.isHideAll = this.index === 1 ? true : false;
      var showBackgroundAndSubtitle = false;
      _.forEach(val.stream, item =>{
        if(item.hasVideo){
          showBackgroundAndSubtitle = true;
          return;
        }
      })

      this.showBackGround = showBackgroundAndSubtitle;
      this.showSubtitle = showBackgroundAndSubtitle;
      
    },
    onSaveChannel() {
      var option = {
        streamCnt: this.currentRow.streamCnt,
        devs: this.currentRow.devs
      };
      api.onRequest(
        "$method.$set.media.mi.ch" + this.currentRow.index,
        JSON.stringify(option),
        null,
        null,
        function(message, reqReply) {
          var res = JSON.parse(message);
          if (res.code == 0) {
            this.notification("Success", "");
          } else {
            this.showCodeMsg(res.code, this, res.msg);
          }
          ebus.emit("getInputChannelInfo", this);
        }.bind(this)
      );
    },
    uploadBgImg() {
      if (!this.file) {
        return;
      }
      var url = "$method.getUploadUrl.sys.netStorage.share0.info"; //暂时写死，以后不一定只有一个目录
      var option = {
        fileType: "pic",
        fileName: 'background' + this.index + '.jpg',
        fileSize: this.file.size
      };
      option = JSON.stringify(option);
      api.onRequest(url, option, null, null, function(msg, reply) {
          var res = JSON.parse(msg);
          if (res.code == 0) {
            var xhr = new XMLHttpRequest();
            var url = "http://" + getHostName() +  ":8080/_default" + res.data.url.substring(res.data.url.indexOf("default") + 7);
            xhr.open("PUT", url, true);
            xhr.onload = e => {
              var opt = {
                enable: this.bgEnable,
                imgFile: res.data.url
              };
              api.onRequest("$method.$set.media.mi.ch" + this.index + ".background", JSON.stringify(opt), null, null, function(msg2, reply) {
                  var resData = JSON.parse(msg2);
                  if (resData.code == 0) {
                    this.clearUploadedImage();
                    this.getBgUrl();
                    this.notification("Success", "");
                  } else {
                    axios.delete(url, { 
                      headers: {'Authorization': "Bearer " + this.system.JWT}
                    }).then(res => {
                      //预留
                    });
                    this.showCodeMsg(resData.code, this, resData.msg);
                  }
                }.bind(this)
              );
            };
            xhr.onerror = (e) =>{              
              this.notification("error", e);
            };
            xhr.setRequestHeader("Authorization", "Bearer " + this.system.JWT);  
                
            xhr.send(this.file);
          }
        }.bind(this)
      );
    },
    onSaveSutitle() {
      var option = {
        enable: this.subtitle.enable ? 1 : 0,
        type: this.subtitle.type,
        fontSize: parseInt(this.subtitle.fontSize),
        foreColor: this.subtitle.foreColor,
        backColor: this.subtitle.backColor,
        content: this.subtitle.content,
        pos: this.subtitle.pos,
        base: {
          h: 100,
          v: 100
        }
      };

      api.onRequest(
        "$method.$set.media.mi.ch" +
          this.currentRow.index +
          ".subtitle" +
          this.subtitle.index,
        JSON.stringify(option),
        null,
        null,
        function(msg, reqReply) {
          var res = JSON.parse(msg);
          if (res.code == 0) {
            this.notification("Success", "");
            ebus.emit("getInputChannelInfo", this);
            this.subtitleVisible = false;
          } else {
            this.showCodeMsg(res.code, this, res.msg);
          }
        }.bind(this)
      );
    },
    editSubtitle(index, row) {
      this.subtitleVisible = true;
      for(var protoName in row){
        this.subtitle[protoName] = row[protoName];
      }  
      this.showSubContent = row.type == 'text' ? true : false;
    },
    editStreamVideo(index, row) {
      this.streamVisible = true;
      this.video = JSON.parse(JSON.stringify(row.video)) ;

      var res = _.find(this.topics, item => {
        return item.topicId == `media.mi.ch${this.index}.stream${index}.vcodec`
      })
      if(res && res.$dataCfg.schemaId == 'media/sVCocecV2.json'){
        this.vprotos = ['H264', 'H265']
      } else{
        this.vprotos = ['H264']
      }
    },
    editStreamAudio(index, row) {
      this.audioVisible = true;
      this.audio.index = row.audio.index;
      this.audio.protocol = row.audio.protocol;
    },
    onFileChange(file) {  
      //校验是否为.jpg格式
      var arrFilename = file.name.split('.');
      var sufName = arrFilename[arrFilename.length - 1];      
      if(sufName != 'jpg'){
        this.notification('error', this.$t('message.medias.typeErr'));
        return;
      }

      this.file = file;  
      this.file.name = 'background' + this.index + '.jpg';   
    },
    arrToStr(arr) {
      var str = "";
      if (arr) {
        str = arr.join();
      }
      return str;
    },
    checkNumVal(val, min, max, callback) {
      if (val < min || val > max) {
        return callback(new Error(min + "~" + max));
      }
    },
    intervalGetInputChnnlInfo() {
      this.interval = setInterval(() => {
        // ebus.emit("getInputChStreamReport", this);
      }, 3000);
    },
    onSubTypeChange(e){
      if(this.subtitle.type == 'text'){
        this.showSubContent = true;
      } else{
        this.showSubContent = false;
      }
    },
    drawLayout() {   
      
      var canvas = document.getElementById("myCanvas");
      // var ctx = canvas.getContext("2d");
      var ctx = getMyCanvas();
      ctx.fillStyle = "#000";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.font = this.subtitle.fontSize + 'px sans-serif';
      ctx.textBaseline = "top";
      ctx.fillStyle = this.subtitle.foreColor    
      
      var x = 0;
      if (this.subtitle.pos.x < 0) {
        var posX = 0;
        var showLen = this.subtitle.content.length * this.subtitle.fontSize / 30;
        if (showLen < 100) {
          posX = (100 - showLen) / 2;
        }
        x = canvas.width * posX / 100;
      } else {
        x = canvas.width * this.subtitle.pos.x / 100;
      }
      var y = canvas.height * this.subtitle.pos.y / 100;
      ctx.fillText('Example', x, y);
    },
    showContent(row){      
      if(row.type == 'text'){
        return row.content;
      } else{
        if(row.type){
          return `{${row.type}}`;
        } else{
          return '';
        }
        
      }
    },
    handlePictureCardPreview(file){
      this.dialogImageUrl = window.URL.createObjectURL(this.file); 
      this.dialogVisible = true;
    },
    getBgUrl(){
      api.onRequest( "$method.$get.media.mi.ch" + this.index + ".background", null, null, null, function(msg2, reply) {
          var resData = JSON.parse(msg2)
          if(resData.code == 0){  
            this.defaultUrl = resData.data.imgFile
            this.imgFile = 'http://' + getHostName() + ":8080/_" + resData.data.imgFile.substr(resData.data.imgFile.indexOf('default'), resData.data.imgFile.length -resData.data.imgFile.indexOf('default')) +'?'+Math.random()
          }
        }.bind(this)
      );
    },
    onBgEnableChanged(val){      
      if(!this.defaultUrl){
        return;
      }
      var opt = {
        enable: val,
        imgFile: this.defaultUrl
      }
      api.onRequest(
        "$method.$set.media.mi.ch" + this.index + ".background",
        JSON.stringify(opt),
        null,
        null,
        function(msg2, reply) {
          var resData = JSON.parse(msg2);
          if (resData.code == 0) {
            this.notification("Success", "");
          } else {
            if(this.bgEnable){
              this.bgEnable = false;
            } else{
              this.bgEnable = true;
            }            
            this.showCodeMsg(resData.code, this, resData.msg);
          }
        }.bind(this)
      );
    },
    onClickExpand(row, exRow){ 
      
      if(this.timer[row.index]){
        clearInterval(this.timer[row.index]);
      }      
      if(this.expanded){        
        this.expanded = false;
      } else{        
        this.timer[row.index] = setInterval(()=>{
          api.onRequest('$method.$get.media.mi.ch' + this.index + '.stream' + row.index + ".streamreport", null, null, null, function (message, reqReply) {                    
            var vcodecData = JSON.parse(message);
            if (vcodecData && vcodecData.code == 0 && vcodecData.data) {
              vcodecData.data.index = row.index;
              var req ={
                index: this.index,
                stream: {
                  index: row.index,
                  report: vcodecData.data
                }
              }
              this.$store.dispatch("media/getInputStream", req);              
              row.report = vcodecData.data
            }
          }.bind(this))
        }, 2000)        
        this.expanded = true;
      }     
      
    },
    onClearInterval(){
      if (this.interval) {
        clearInterval(this.interval);
      }
      for(var timer of this.timer){
        if(timer){
          clearInterval(timer);
        }
      }
    },
    onSubDialogOpen(){
      setTimeout(()=>{
        this.drawLayout();
      }, 200);
    },
    getSubtitleDataByIndex(){
     api.onRequest('$method.$get.media.mi.ch' + this.index + '.subtitle' + this.subtitle.index + "", null, null, null,  (message, reqReply)=> {
        var res = JSON.parse(message);
        if(res.code == 0){
          this.subtitleData[this.subtitle.index] = res.data;
          this.subtitleData[this.subtitle.index].index= this.subtitle.index;
          console.log('this.subtitleData[this.subtitle.index]:', this.subtitleData[this.subtitle.index]);
        }
     })
    },
    clearUploadedImage () {
      this.$refs.upload.clearFiles();
    },
    onFilesOutOfMax(files, fileList){
      //校验是否为.jpg格式
      var arrFilename = files[0].name.split('.');
      var sufName = arrFilename[arrFilename.length - 1];      
      if(sufName != 'jpg'){
        this.notification('error', this.$t('message.medias.typeErr'));
        return;
      }
      this.file = files[0];
      var upload = document.getElementById('imgUploadFile');     
      upload.children[0].children[0].children[0].src =  window.URL.createObjectURL(files[0]); 
    },
    onSelectFile(file){
      var arrFilename = file.name.split('.');
      var sufName = arrFilename[arrFilename.length - 1];      
      if(sufName != 'jpg'){
        this.notification('error', this.$t('message.medias.typeErr'));
        return;
      }
    },
    onSelectDevChange (newVal, index) {  
      // 实现Dev0和Dev1互斥    
      var devs = this.currentRow.devs      
      if (index === 0 || index === 1) {
        if (devs && devs.length) {
          devs.forEach((item, itemIndex) => {          
            if ((item === 0 || item === 1) && item !== index) {
              devs.splice(itemIndex, 1);
            }
          })
        }
      }  
      devs.sort();       
    }
  }
};
</script>

<style @scoped>
.el-form-item__content select {
  height: 28px;
}
.el-slider{
  width:300px;
  margin-left: 126px;
}
</style>

